package org.fxcontainer.commands.navigation.chain
{
	import com.developmentarc.core.actions.commands.AbstractCommand;
	

	/**
	 * Represents navigation URL. 
	 * @author Izzet_Mustafayev
	 */
	public final class NavigationURL
	{
		/**
		 * The URL to navigate to. 
		 */
		private var url:String = "";
		
		/**
		 * The page name to navigate to. 
		 */
		private var page:String;
		
		/**
		 * Holds control invocation URLs
		 * @default 
		 */
		private var controls:Array = new Array();
		
		/**
		 * Adds page to navigation URL.  
		 * @param pageName the page name to add
		 */
		public function addPage(pageName:String):void
		{
			if (null != pageName){
				this.url += "/"+pageName;
			}
		}
		
		/**
		 * Adds control to invoke after navigation succeed. 
		 * @param controlName the control name to invoke
		 * @param methodName the method name to invoke on control
		 * @param args the control method arguments. Could be nullable 
		 */
		public function touchControl(controlName:String, methodName:String, ... args:Array):void
		{	
			if (null != controlName){
				addControl(controlName, methodName, args!=null&&args[0]!=null&&args[0] is Array?args[0]:args);
			}
			if (null != controlName && url.indexOf("##control##")<=0){
				this.url += "/##control##";
			}
		}
		
		private function addControl(controlName:String, methodName:String, ... args:Array):void
		{
			if(null != args && args[0] != null &&  args[0] is Array){
				args = args[0];
			}
			var urlString:String = "";
			if (null != controlName){
				urlString += controlName;
			}
			if (null != methodName){
				urlString += "::"+methodName;
			}
			if (null != args && args.length>0){
				urlString+="::";
				var argsLen:int = args.length;
				var count:int = args.length;
				for (var i:int=0; i<argsLen; i++){
					var arg:* = args[i];
					//we gather only primitives
					if (arg is String || arg is int || arg is Number){
						urlString+=arg;
						count--;
						if(count>0){
							urlString+="||";
						}
					}
				}
			}
			controls.push(urlString);
		}
		
		public function touchControlQueue(command:AbstractCommand, controlName:String, methodName:String=null, ... args:Array):ControlQueue
		{
			var controlQueue:ControlQueue = new ControlQueue(this, command);
			controlQueue.touchControl(controlName, methodName, args!=null?args[0]:args);
			return controlQueue;
		}
		
		/**
		 * Transform gathering objects to string URL representation.
		 * @return the URL to navigate to
		 */
		public function toURL():String
		{
			if(controls.length>0){
				var controlURL:String = "{";
				var count:int = controls.length;
				for(var i:int=0; i<controls.length; i++){
					controlURL+=controls[i];
					count--;
					if(count>0){
						controlURL+=";;";
					}
				}
				controlURL+="}";
				this.url = this.url.replace("##control##", controlURL);
			}
			return this.url;
		}
	}
}